<?php declare(strict_types=1);

namespace App\Util\Rsa;

class Rsa2Util
{

    public static function getSign(string $public, array $data): string
    {
        unset($data["sign"]);
        //先过滤参数为空的数据
        foreach ($data as $k => $v) {
            if (empty($v)) {
                unset($data[$k]);
            }
        }
        ksort($data);
        $str = "";
        foreach ($data as $k => $v) {
            $str .= $k . "=" . $v . "&";
        }
        $str = rtrim($str, "&");
        //获取算法
        $sha256 = hash('sha256', $str);
        //在进行rsa
        $key_pem =
            "-----BEGIN PUBLIC KEY-----
" .
            chunk_split(
                $public,
                64,
                "
"
            ) .
            "-----END PUBLIC KEY-----";

        $publicKey = openssl_pkey_get_public($key_pem); //检测是否公钥
        openssl_public_encrypt($sha256, $sign, $publicKey); //公钥加密
        $sign = base64_encode($sign);
        return $sign;
    }



    public static function decode(string $public,string $sign): string
    {
        $RSA_DECRYPT_BLOCK_SIZE = 256;
        $sign = base64_decode($sign);
        $data = str_split($sign, $RSA_DECRYPT_BLOCK_SIZE);
        $key_pem =
            "-----BEGIN PUBLIC KEY-----
" .
            chunk_split(
                $public,
                64,
                "
"
            ) .
            "-----END PUBLIC KEY-----"; // 公钥
        $pubKey = openssl_pkey_get_public($key_pem);
        $result = "";
        foreach ($data as $block) {
            openssl_public_decrypt($block, $dataDecrypt, $pubKey);
            $result .= $dataDecrypt;
        }
        return $result;
    }



}